home *** CD-ROM | disk | FTP | other *** search
- /*
- * conio.c,v 1.0 1996/03/18 14:18:33 miksic Exp
- */
-
- /*
- * Implementation of kbhit(), getch() and getche() functions in Linux
- */
-
- #include <termios.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/time.h>
- #include <errno.h>
- #include "conio.h"
-
- static struct termios normal_terms;
- static int tty;
-
- static void go_raw( void );
- static void no_echo( void );
- static int get_char_wait( void );
-
- void
- get_normal_terms( void )
- {
- tcgetattr( fileno( stdin ), &normal_terms );
- tty = fileno( stdin );
- }
-
- void
- go_normal_terms( void )
- {
- tcsetattr( fileno( stdin ), TCSANOW, &normal_terms );
- }
-
- int
- kbhit( void )
- {
- fd_set fd;
- struct timeval timeout;
- go_raw();
- FD_ZERO( &fd );
- FD_SET( tty, &fd );
- timeout.tv_sec = timeout.tv_usec = 0;
- while( 0 > select( FD_SETSIZE, &fd, NULL, NULL, &timeout )
- && errno == EINTR );
- go_normal_terms();
- return FD_ISSET( tty, &fd );
- }
-
- int
- getch( void )
- {
- go_raw();
- no_echo();
- return get_char_wait();
- }
-
- int
- getche( void )
- {
- go_raw();
- return get_char_wait();
- }
-
- static void
- go_raw( void )
- {
- struct termios terms;
- tcgetattr( tty, &terms );
- terms.c_lflag &= ~ICANON;
- terms.c_cc[VMIN] = terms.c_cc[VTIME] = 0;
- tcsetattr( tty, TCSANOW, &terms );
- }
-
- static void
- no_echo( void )
- {
- struct termios terms;
- tcgetattr( tty, &terms );
- terms.c_lflag &= ~ECHO;
- tcsetattr( tty, TCSANOW, &terms );
- }
-
- static int
- get_char_wait( void )
- {
- int ch;
- fd_set fd;
- FD_ZERO( &fd );
- FD_SET( tty, &fd );
- while( 0 > select( FD_SETSIZE, &fd, NULL, NULL, NULL )
- && errno == EINTR );
- ch = getchar();
- go_normal_terms();
- return ch;
- }
-